package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.UserLike;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

@DubboService
public class UserLikeApiImpl implements UserLikeApi{
    @Autowired
    private MongoTemplate mongoTemplate;


    /**
     *保存或更新喜欢的用户信息
     */
    public Boolean saveOrUpdate(Long userId, Long likeUserId, boolean isLike) {

        try {
            //1.先查询UserLike表是否有数据
            Criteria criteria = Criteria.where("userId").is(userId).and("likeUserId").is(likeUserId);
            Query query = Query.query(criteria);

            UserLike userLike  = mongoTemplate.findOne(query, UserLike.class);
            if(userLike == null){
                //没有，保存数据
                userLike = new UserLike();
                userLike.setUserId(userId);
                userLike.setLikeUserId(likeUserId);
                userLike.setCreated(System.currentTimeMillis());
                userLike.setIsLike(isLike);
                mongoTemplate.save(userLike);
            }else{
                //有数据，更新数据
                Update update = Update.update("isLike", isLike).set("updated", System.currentTimeMillis());

                mongoTemplate.updateFirst(query, update, UserLike.class);
            }

            return true;
        }catch (Exception e){
            e.printStackTrace();

            return false;
        }
    }
}
